# 字符串，帮助类
import base64
import hashlib
import hmac
import json
import urllib
import urllib.parse
import re


def url_encode(s):
    return urllib.parse.quote(s)


def url_decode(s):
    return urllib.parse.unquote(s)


def split2(s, s1=";", s2="@") -> list | None:
    """
    abc@a111;cba@a222 转 [[abc,a111],[cba,a222]]
    :param s:
    :param s1: 1级分隔符
    :param s2: 2级分隔符
    :return: 字符串数组
    """
    if is_null_or_empty(s):
        return None

    arr = s.split(s1)
    res_arr = []
    for v in arr:
        if is_null_or_empty(v):
            continue
        item_arr = v.split(s2)
        res_arr.append(item_arr)

    return res_arr


def contains(s, pattern):
    """
    字符串模糊查找
    :param s:
    :param pattern: 查找的字符串，可以是字符串数组
    :return:
    """
    if isinstance(pattern, list):
        pattern = '|'.join(map(str, pattern))

    match = re.search(pattern, s)
    return match is not None


def is_null_or_empty(s):
    if s is None:
        return True
    if s == "" or s == "undefined" or s == "null":
        return True

    return False


def has_any_text(s):
    return not is_null_or_empty(s)


def to_json_str(obj):
    return json.dumps(obj)


# 二进制转字符串
def bytes_to_str(s):
    if s is None:
        return None

    if isinstance(s, str):
        return s

    return s.decode('UTF-8').strip()


# 字符串转二进制
def str_to_bytes(s):
    return bytes(s, 'UTF-8')


# 返回a=1&b=2
def map_to_query(data):
    if data is None:
        return ''
    if not isinstance(data, dict):
        return ''

    str = ''
    for k, v in data.items():
        str += f"{k}={v}&"

    return str[:len(str) - 1]


# HMAC-SHA256加密
def hmacSHA256(data, secret_key):
    hmac_sha256 = hmac.new(secret_key.encode('utf-8'), data.encode('utf-8'), hashlib.sha256)
    hmac_code = hmac_sha256.digest()
    return urllib.parse.quote_plus(base64.b64encode(hmac_code))


# 转int
def to_int(s, d=None):
    v = to_type(s, int)
    if v is None:
        v = d
    return v


# 转任意类型
def to_type(s, to):
    num = None
    try:
        num = to(s)
    except Exception as ex:
        num = None
    return num


def sub(s: str, len: int):
    """
    字符串截取指定长度
    :param s:
    :param len: 长度
    """
    return s[0:len]


def sub_byte(s: str, len: int):
    """
    字符串截取指定字节长度
    :param s:
    :param len: 长度
    """
    bytes_str = s.encode("utf-8")
    cut_bytes = bytes_str[0:len]
    return cut_bytes.decode("utf-8")
